#!/bin/bash

scriptPath=$(dirname $0);
echo "sequence analysis (sequence.eps)"

cat $scriptPath/sequence-gnuplot.begin > seq.gplot

# min and max time
minTime=$(sqlite3 -batch trace.sqlite "SELECT min(e.time) FROM eventsContentOnly as e WHERE eventName='EVENT_TYPE_DATAOBJECT_NEW';")
maxTime=$(sqlite3 -batch trace.sqlite "SELECT max(e.time) FROM eventsContentOnly as e WHERE eventName='EVENT_TYPE_DATAOBJECT_NEW';")

# select unit (min or hour; threshold 200min)
longDuration=$(sqlite3 -batch trace.sqlite "SELECT max(e.time)-min(e.time)>200*60 FROM eventsContentOnly as e WHERE eventName='EVENT_TYPE_DATAOBJECT_NEW';")
if [ $longDuration == "1" ]
then ticks=3600; sed 's/UNIT/h/' seq.gplot > sequence.gplot
else ticks=60; sed 's/UNIT/min/' seq.gplot > sequence.gplot
fi
rm seq.gplot
	
# number of data objects	
numDObj=$(sqlite3 -batch trace.sqlite "select count(*) from (select * from eventsContentOnly group by substr(dataobjectId,0,40));")


i=0
for logPath in $(ls -1d */)
do
	logPath=$(echo $logPath | sed 's/\///')
	if [ -f $logPath/title ]
	then device=$(cat $logPath/title);
	else device=$logPath;
	fi

	i=$[i+1]
	sqlite3 -batch -separator ' ' trace.sqlite "SELECT e.time as t FROM eventsContentOnly as e WHERE e.eventName='EVENT_TYPE_DATAOBJECT_NEW' AND  e.device='$device' ORDER BY t;" | awk '{print $1;}' | awk -v minTime=$minTime -v maxTime=$maxTime 'BEGIN {print 0, cnt} {cnt=FNR; print $1-minTime, cnt;} END {print maxTime-minTime, cnt}' > tmp-sequence-$logPath

	PLOT=$PLOT"\"tmp-sequence-$logPath\" using (\$1/$ticks):(\$2/"$numDObj") with linespoints ls $i t \"$device\","
done
PLOT=`echo $PLOT | sed -e 's/,$//'`
echo "plot "$PLOT >> sequence.gplot

gnuplot sequence.gplot

rm sequence.gplot
rm tmp-sequence*
